package com.yunfeisoft.controller.business;

import com.applet.base.BaseController;
import com.applet.utils.*;
import com.yunfeisoft.business.model.IndecItem;
import com.yunfeisoft.business.model.IndecOrder;
import com.yunfeisoft.business.service.inter.CodeBuilderService;
import com.yunfeisoft.business.service.inter.IndecItemService;
import com.yunfeisoft.business.service.inter.IndecOrderService;
import com.yunfeisoft.model.User;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * ClassName: IndecOrderController
 * Description: 损益单信息Controller
 * Author: Jackie liu
 * Date: 2020-08-06
 */
@Controller
public class IndecOrderController extends BaseController {

    @Autowired
    private IndecOrderService indecOrderService;
    @Autowired
    private CodeBuilderService codeBuilderService;
    @Autowired
    private IndecItemService indecItemService;

    /**
     * 添加损益单信息
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/indecOrder/save", method = RequestMethod.POST)
    @ResponseBody
    public Response save(IndecOrder record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "indecDate", "损益日期为空");
        validator.required(request, "productsStr", "商品为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        User user = ApiUtils.getLoginUser();
        record.setId(KeyUtils.getKey());
        record.setOrgId(user.getOrgId());

        String productsStr = ServletRequestUtils.getStringParameter(request, "productsStr", null);
        List<IndecItem> indecItemList = FastJsonUtils.jsonToList(productsStr, IndecItem.class);

        //BigDecimal totalAmount = BigDecimal.ZERO;
        Iterator<IndecItem> iterator = indecItemList.iterator();
        while (iterator.hasNext()) {
            IndecItem item = iterator.next();
            if (StringUtils.isBlank(item.getProductId())) {
                iterator.remove();
                continue;
            }
            item.setId(KeyUtils.getKey());
            item.setOrgId(user.getOrgId());
            item.setIndecOrderId(record.getId());

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (item.getStock() == null) {
                return ResponseUtils.warn("含有实际库存不合法或者为空的商品");
            }

            if (item.getPrice() == null) {
                return ResponseUtils.warn("含有损益单价不合法或者为空的商品");
            }
        }
        record.setIndecItemList(indecItemList);
        if (CollectionUtils.isEmpty(indecItemList)) {
            return ResponseUtils.warn("商品为空");
        }

        String code = codeBuilderService.generateIndecOrderCode(user.getOrgId());
        record.setCode(code);
        record.setStatus(IndecOrder.IndecOrderStatusEnum.DELIVERED.getValue());

        indecOrderService.save(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 修改损益单信息
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/indecOrder/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modify(IndecOrder record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "id", "参数错误");
        validator.required(request, "indecDate", "损益日期为空");
        validator.required(request, "productsStr", "商品为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        /*IndecOrder indecOrder = indecOrderService.load(record.getId());
        if (indecOrder.getStatus() != IndecOrder.IndecOrderStatusEnum.TO_BE_DELIVERED.getValue()
                && indecOrder.getStatus() != IndecOrder.IndecOrderStatusEnum.TO_BE_CHANGED.getValue()) {
            return ResponseUtils.warn("该订单状态不是【待入库】，也不是【待更改】，无法修改");
        }*/

        User user = ApiUtils.getLoginUser();

        String productsStr = ServletRequestUtils.getStringParameter(request, "productsStr", null);
        List<IndecItem> indecItemList = FastJsonUtils.jsonToList(productsStr, IndecItem.class);

        Iterator<IndecItem> iterator = indecItemList.iterator();
        while (iterator.hasNext()) {
            IndecItem item = iterator.next();
            if (StringUtils.isBlank(item.getProductId())) {
                iterator.remove();
                continue;
            }
            item.setId(KeyUtils.getKey());
            item.setOrgId(user.getOrgId());
            item.setIndecOrderId(record.getId());

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (item.getStock() == null) {
                return ResponseUtils.warn("含有实际库存不合法或者为空的商品");
            }

            if (item.getPrice() == null) {
                return ResponseUtils.warn("含有损益单价不合法或者为空的商品");
            }
        }
        record.setIndecItemList(indecItemList);
        if (CollectionUtils.isEmpty(indecItemList)) {
            return ResponseUtils.warn("商品为空");
        }
        record.setStatus(IndecOrder.IndecOrderStatusEnum.DELIVERED.getValue());

        indecOrderService.modify(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 查询损益单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/indecOrder/query", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response query(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        IndecOrder record = indecOrderService.load(id);
        if (record != null) {
            List<IndecItem> indecItemList = indecItemService.queryByIndecOrderId(id);
            record.setIndecItemList(indecItemList);
        }
        return ResponseUtils.success(record);
    }

    /**
     * 分页查询损益单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/indecOrder/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response list(HttpServletRequest request, HttpServletResponse response) {
        String indecDate = ServletRequestUtils.getStringParameter(request, "indecDate", null);

        User user = ApiUtils.getLoginUser();

        Map<String, Object> params = new HashMap<String, Object>();
        initParams(params, request);
        params.put("orgId", user.getOrgId());
        params.put("indecDate", indecDate);

        Page<IndecOrder> page = indecOrderService.queryPage(params);
        return ResponseUtils.success(page);
    }

    /**
     * 批量删除损益单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/indecOrder/delete", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response delete(HttpServletRequest request, HttpServletResponse response) {
        String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
        if (StringUtils.isBlank(ids)) {
            return ResponseUtils.warn("参数错误");
        }
        indecOrderService.remove(ids.split(","));
        return ResponseUtils.success("删除成功");
    }

    /**
     * 改单解锁
     *
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "/web/indecOrder/changeOrder", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response changeOrder(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        IndecOrder indecOrder = indecOrderService.load(id);
        if (indecOrder.getStatus() != IndecOrder.IndecOrderStatusEnum.DELIVERED.getValue()) {
            return ResponseUtils.success("success");
        }

        indecOrderService.modifyWithUnLock(id);
        return ResponseUtils.success("success");
    }*/
}
